package fun.stgoder.test1;

import java.util.ArrayList;
import java.util.List;

public class TestWaitNotify {

    private static int n = 0;

    public static void main(String[] args) {

        Object o = new Object();

        List<Integer> list = new ArrayList<>();

        new Thread(() -> {

            synchronized (o) {

                System.out.println("t0");

                while (list.size() != 5) {
                    try {
                        System.out.println("t0 size != 5, == " + list.size() + ", wait");
                        o.wait();
                        System.out.println("t0 size == " + list.size() + ", exit");
                        o.notify();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }).start();

        TestUtil.sleepSeconds(1);

        new Thread(() -> {
            synchronized (o) {

                System.out.println("t1");

                for (int i = 0; i < 20; i++) {
                    list.add(i);
                    System.out.println("add " + i);
                    if (list.size() == 5) {
                        o.notify();
                        try {
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    TestUtil.sleepSeconds(1);
                }

                System.out.println("t1 exit");
            }

        }).start();

    }
}
